#!/usr/bin/python3.5

# -*- coding: utf-8 -*-

class Solution:
    def threeSumClosest(self, nums,target):
         n = len(nums)
         if n<=3:
             return sum(nums)
         nums.sort()
         mind = abs(nums[n-1] + nums[n-2] + nums[n-3] - target)
         i=0
         mintarget = abs(nums[n-1] +  nums[n-2] + nums[n-3])
         while i< n-2:
             k = i+1
             m = n-1
             while k < m:
                 sum3 = nums[i]+nums[k]+nums[m]
                 if abs(sum3 - target) < mind:
                     mind = abs(sum3 - target)
                     mintarget = sum3
                 if sum3 < target:

                     k+=1
                 elif sum3==target:
                     return target
                 else:

                     m-=1
             i+=1
         return  mintarget




if __name__ == '__main__':
        # arr=[int(x) for x in input().strip().split(' ')]
        arr =    [0,2,1,-3]


        target = 1

        a = Solution().threeSumClosest(arr, target)
        print(a)

